// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE

#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif defined(_MSC_VER)
#pragma warning(disable : 4996)
#endif

/* This executable is used for testing parser/writer using real JSON files.
 */

#include <json/json.h>
#include <algorithm> // sort
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <readline/readline.h>



int main(int argc, const char* argv[]) {
  int fd;
  struct sockaddr_in address;
  int address_len;
  int rtval;
  char* data = "adfdasf";
  char data2[200];
  int len;
  fd = socket(AF_INET, SOCK_STREAM, 0);
  
  printf ("will connect %s %s\n", argv[1], argv[2]);
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = inet_addr(argv[1]);
  address.sin_port = htons(atoi(argv[2]));
  address_len = sizeof(address);

  rtval = connect(fd, (struct sockaddr*)&address, address_len);
  if (rtval == -1) {
    printf ("connect fail!\n");
    return -1;
  }

    Json::Value root;
    Json::FastWriter writer;
    Json::Value person;
 
    person["Address"] = "EWQE1123AD32";
    person["CommandType"] = "0001";
    person["Check"] = "XXXXX";
    root.append(person);
 
    //std::string json_file = writer.write(root);
    std::string json_file = writer.write(person);
    printf ("send:%s\n", json_file.c_str());
    write(fd, json_file.c_str(), json_file.size());
    write(fd, "#", 1);

  while((len = read(fd, (void*)data2, 200)) > 0) {
      printf ("data2(%d)=%s\n", len, data2);
      std::string data2str{ data2 };
    Json::Reader reader;
    Json::Value root2;
    if (!reader.parse(data2str, root2, false))
    {
      printf ("parse json fail!\n");
      return -1;
    }
      printf ("parse json ok! %s %s\n", root2["CommandType"].asString().c_str(), root2["RespCode"].asString().c_str());
  }
  close(fd);
  return 0;
}

#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
